package com.test.nio.select.book;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Scanner;
import java.util.Set;

/**
 * @Description:
 * @Author: yangzhiwei
 * @Date: 2021/8/2 14:30
 */
public class SelectClient {
    public static void main(String[] args) throws IOException {
        SocketChannel channel = SocketChannel.open();
        InetSocketAddress inetSocketAddress =
                new InetSocketAddress("127.0.0.1",20010);
        channel.configureBlocking(false);
        boolean flag = channel.connect(inetSocketAddress);
        System.out.println("connectionFlag:" + flag);
        Selector selector = Selector.open();
        //Selector selector1 = Selector.open();
        //SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_READ);
        SelectionKey selectionKey1 = channel.register(selector, SelectionKey.OP_WRITE
                |SelectionKey.OP_READ
                |SelectionKey.OP_CONNECT);
//        System.out.println("selectionKey valid?" + selectionKey.isValid());
//        System.out.println(selectionKey);
        System.out.println("selectionKey valid?" + selectionKey1.isValid());
        System.out.println(selectionKey1);
        //channel.register(selector1,SelectionKey.OP_WRITE);
        //selector.selectedKeys();
        //selector.keys();
//        selectionKey.cancel();
//        channel.isRegistered();


        //改变监听的时间
//

//        selectionKey.readyOps();

     //   System.out.println(channel.validOps());

        /**
         * selector 可执行的操作
         * select
         * selectKeys
         */
        //Set<SelectionKey> selectionKeys = selector1.selectedKeys();

        //select( )方法在将线程置于睡眠状态，直到这些刚兴趣的事情中的操作中的一个发生或者 10 秒钟的时间过去。
        //int readCount = selector.select(10);
//        SelectorProvider selectorProvider = selector.provider();
//        selectorProvider.openDatagramChannel()

        SocketChannel socketChannel = (SocketChannel)selectionKey1.channel();


        ByteBuffer byteBuffer = ByteBuffer.allocate(100);
        byteBuffer.put("你好服务器，我是客户端1".getBytes());
        //byteBuffer.get();
        byteBuffer.flip();
        //System.out.println(byteBuffer.toString());
        System.out.println(socketChannel.isConnected());
        socketChannel.write(byteBuffer);
       // socketChannel.close();
        Scanner in = new Scanner(System.in);
        String s ;
        while ((s = in.nextLine()) != null || socketChannel.isConnected()) {
            System.out.println("connecting......");
            byteBuffer.reset();
            byteBuffer.put(s.getBytes());
            byteBuffer.flip();
            channel.write(byteBuffer);
        }




    }
}
